<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px">
        <el-row :gutter="10">
          <el-col :span="6" :xs="24">
            <el-form-item label="产品名称">
              <el-input v-model="page.productName"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24" v-permiss="['product-institution']">
            <el-form-item label="所属机构">
              <el-select v-model="page.institutionId" clearable style="width: 100%">
                <el-option v-for="item in institutionList" :key="item.name" :label="item.name"
                           :value="item.institutionId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="产品状态">
              <el-select v-model="page.status" style="width: 100%" clearable>
                <el-option v-for="item in productStatus" :key="item.value" :value="item.value"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item label="所属贷超APP"  label-width="120px">
            <el-select v-model="page.appId"  clearable>
              <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                         :value="item.appId"></el-option>
            </el-select>
          </el-form-item>
          <el-col :span="10" :xs="24">
            <el-form-item label="创建时间">
              <el-date-picker
                  style="width: 100%"
                  v-model="page.createTimeValue"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getTableData">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <div style="text-align: right;margin-bottom: 10px">
      <el-button type="primary" icon="el-icon-plus" v-permiss="['product-add']" @click="addProduct">添加产品</el-button>
    </div>
    <Table :tableColumn="tableColumn" :tableData="tableData" :page="page"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
           :loading="tableLoading"
    >
      <template #status="{row}">
        {{ productStatus.find(item => item.value === row.status).label }}
      </template>
      <template #logoUrl="{row}">
        <el-image v-if="row.logoUrl" style="width: 80px;height: 80px" :src="row.logoUrl"
                  :preview-src-list="[row.logoUrl]"></el-image>
      </template>
      <template #loanMaxLimit="{row}">
        {{ row.loanMinLimit }} - {{ row.loanMaxLimit }}
      </template>
      <template #feeType="{row}">
        {{ row.feeType === 1 ? 'CPA订单量' : 'CPS放款量' }}
      </template>
      <template #handle="{row}">
        <el-button type="text" v-permiss="['product-edit']" @click="productChange(row,'put')">{{
            row.status === 0 || row.status === 2 ? '上架' : '下架'
          }}
        </el-button>
        <el-button type="text" @click="editProduct(row)" v-permiss="['product-edit']">编辑</el-button>
        <el-button type="text" @click="changeTopScore(row)" v-if="row.status === 1" >{{ row.topScore ? '取消置顶' : '置顶' }}
        </el-button>
        <el-button type="text" @click="productChange(row,'del')" v-permiss="['product-delete']"
                   v-show="row.status === 0 || row.status === 2">删除
        </el-button>
        <el-button type="text" @click="configProduct(row)" v-permiss="['product-config']">综合配置</el-button>
      </template>
    </Table>
    <!--     添加，编辑产品-->
    <Dialog v-model="productVisible.isShow" :title="productVisible.title" width="55%"
            @cancel="productVisible.isShow = false"
            :footer="productVisible.type !== 'edit' || productRows.status !== 1"
            @confirm="productConfirm"
            @close="productFormClear"
    >
      <productEdit ref="product" :visible="productVisible.isShow" :type="productVisible.type"
                   :productInfo="productRows"/>
    </Dialog>

    <!--    综合配置-->
    <Dialog v-model="productConfig.isShow" :title="productConfig.title" width="55%"
            @cancel="productConfig.isShow = false"
            @confirm="productConfigConfirm"
            @close="productConfigClear"
    >
      <comperehensive-config ref="config" :config="productRows"/>
    </Dialog>
  </el-card>
</template>

<script>
import {defineComponent, onMounted, reactive, ref, toRefs, computed} from 'vue'
import {fetchProduct, updateStatusProduct, updateTopScore} from "@/api/product";
import {selectInstitution,selectProductList} from "@/api";
import productEdit from './productEdit/index'
import ComperehensiveConfig from './comprehensiveConfig'
import {ElMessage, ElMessageBox} from "element-plus";
import {dateFormatTimeStamp} from '@/utils/index'

const tableColumn = [
  {label: '产品名称', prop: 'productName', align: 'center', minWidth: 150},
  {label: '所属贷超APP', prop: 'appName', align: 'center', minWidth: 150},
  {label: '所属机构', prop: 'name', align: 'center', minWidth: 150},
  {label: '产品URL', prop: 'requestUrl', align: 'center', minWidth: 150},
  {label: '产品logo', prop: "logoUrl", slot: 'logoUrl', align: "center", minWidth: 150,},
  {label: '可贷范围', prop: 'loanMaxLimit', slot: 'loanMaxLimit', align: 'center', minWidth: 150},
  {label: '收费方式', prop: 'feeType', slot: 'feeType', align: 'center', minWidth: 150},
  {label: '产品状态', slot: 'status', align: 'center',},
  {label: '创建时间', prop: 'createTime', align: 'center', minWidth: 150},
  {label: '创建人', prop: 'createName', align: 'center', minWidth: 150},
  {label: '操作', slot: 'handle', align: 'center', fixed: 'right', minWidth: 150},
]
const productStatus = [
  {label: '待上架', value: 0},
  {label: '已上架', value: 1},
  {label: '已下架', value: 2,},
]
export default defineComponent({
  name: "ProductList",
  components: {
    productEdit,
    ComperehensiveConfig
  },
  setup() {
    const product = ref(null)
    const config = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      productVisible: {
        isShow: false,
        type: 'add',
        title: '添加产品'
      },
      productConfig: {
        isShow: false,
        title: ''
      },
      tableData: [],
      tableLoading:false,
      productRows: {},
      productList:[],
      institutionList: []
    })
    const getTableData = async () => {
      state.tableLoading = true
      const [createStartTime, createEndTime] = dateFormatTimeStamp(state.page.createTimeValue)
      const params = {
        createStartTime, createEndTime,
        ...state.page
      }
      delete params.createTimeValue
      const res = await fetchProduct(params)
      if (res.code === 200) {
        const {list, total} = res.data
        state.tableData = list
        state.page = {
          ...state.page,
          total
        }
        state.tableLoading = false
      }
    }
    const resetSearch = () => {
      state.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      getTableData()
    }
    const addProduct = () => {
      state.productVisible = {
        isShow: true,
        type: 'add',
        title: '添加产品'
      }
    }
    const editProduct = (row) => {
      state.productVisible = {
        isShow: true,
        type: 'edit',
        title: '编辑产品'
      }
      state.productRows = {...row}
    }
    const configProduct = (row) => {
      state.productConfig = {
        isShow: true,
        title: '综合配置'
      }
      state.productRows = {...row}
    }
    // 产品配置清除
    const productConfigClear = () => {

      config.value.clearForm()
    }
    //产品配置提交回调
    const productConfigConfirm = async () => {
      const code = await config.value.confirmSubmit()
      if (code) {
        state.productConfig.isShow = false
        getTableData()
      }
    }
    /*
    * 产品提交回调
    * */
    const productConfirm = async () => {
      const code = await product.value.submitForm()
      if (code) {
        state.productVisible.isShow = false
        getTableData()
      }
    }
    const productFormClear = () => {
      product.value.clearForm()
    }
    /*
    * 产品状态切换
    * */
    const productChange = async (row, type) => {
      ElMessageBox.confirm('确认进行此操作?', '提示', {
        type: 'warning',
      }).then(async () => {
        const params = {
          productId: row.productId
        }
        if (type === 'del') {
          params.status = 3
        } else {
          // 待上架 || 下架
          if (row.status === 0 || row.status === 2) {
            params.status = 1
          } else {
            // 已上架
            params.status = 2
          }
        }
        const res = await updateStatusProduct(params)
        if (res.code === 200) {
          ElMessage.success({
            message: '操作成功'
          })
          getTableData()
        }
      }).catch(() => {

      });
    }
    const getSelect = () => {
      selectInstitution().then(res => {
        if (res.code === 200) {
          state.institutionList = res.data
        }
      })
      selectProductList().then(res => {
        if (res.code === 200) {
          state.productList = res.data
        }
      })
    }
    const changeTopScore = ({productId, topScore}) => {
      ElMessageBox.confirm('确认进行此操作?', '提示', {
        type: 'warning',
      }).then(async () => {
        const res = await updateTopScore({
          status: topScore ? 0 : 1,
          productId
        })
        if (res.code === 200) {
          ElMessage.success({
            message: '操作成功'
          })
          getTableData()
        }
      }).catch(() => {

      });
    }
    onMounted(() => {
      getTableData()
      getSelect()
    })
    return {
      changeTopScore,
      tableColumn,
      ...toRefs(state),
      productStatus,
      getTableData,
      resetSearch,
      addProduct,
      editProduct,
      product,
      config,
      productConfirm,
      productChange,
      productFormClear,
      productConfigClear,
      productConfigConfirm,
      configProduct
    }
  }
})
</script>

<style scoped>

</style>
